package cn.tuling.org.controller;

import cn.tuling.org.domain.User;
import cn.tuling.org.service.LoginUserService;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
 * 登录控制类
 */
@CrossOrigin(origins = {"*"})
@RestController
@RequestMapping("/login")
public class LoginController {

    @Autowired
    private LoginUserService loginUserService;

    @PostMapping
    public Map login(@RequestBody String username, HttpSession session) {
        Map result = new HashMap<String, Object>();
        System.out.println("username:"+username.toString());
        Map mapTypes = JSON.parseObject(username);
        username=(String) mapTypes.get("username");
        System.out.println();
        if (username != null) {
            User user = loginUserService.findLoginUser(username);
            System.out.println(user);
            if (username.equals("admin")) {
                session.setAttribute("admin", username);
                result.put("code",200);
                result.put("msg","请求成功");
                result.put("user",username);
            } else if (user != null && user.getState().equals("启用")) {
                session.setAttribute("user", user);
                System.out.println(session.getId());
                result.put("code",200);
                result.put("msg","请求成功");
                result.put("user",user.getUsername());
            }else {
                result.put("msg","用户未启用或不存在");
                result.put("code",500);
            }
        }else {
            result.put("msg","亲,很抱歉!我们遇到点错误,请稍后重试!");
            result.put("code",500);
        }
        return result;
    }
}
